package cn.ch.org.service.impl;

import cn.ch.basic.exception.BusinessException;
import cn.ch.basic.service.impl.BaseServiceImpl;
import cn.ch.basic.util.BaiduAuditUtils;
import cn.ch.org.domain.Employee;
import cn.ch.org.domain.Shop;
import cn.ch.org.domain.ShopAuditLog;
import cn.ch.org.domain.ShopVo;
import cn.ch.org.mapper.EmployeeMapper;
import cn.ch.org.mapper.ShopAuditLogMapper;
import cn.ch.org.mapper.ShopMapper;
import cn.ch.org.service.IEmployeeService;
import cn.ch.org.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Why
 * @since 2022-02-11
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    /**
     *
     * @param shop
     */
    /**
     *一：参数校验
     *         //1.空校验 密码要一致
     *         //2.非法校验（百度AI智能审核） 名称、图片
     *二：业务校验
     *         //1.店铺不能被注册
     *         //2.employee是否曾今注册过了
     *三：存储
     *         //1.存储shop
     *         //2.存储employee
     *
     * @param shop
     */
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private IEmployeeService employeeService;//会从service里面去调用另一个service，是业务高度疯转的表现
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;
    @Autowired
    private JavaMailSender javaMailSender; //与邮件发送相关


    @Override
    @Transactional
    public void settlement(Shop shop) {
        /*一. 参数校验*/
        //1.空校验
        if(StringUtils.isEmpty(shop.getName())){//验证shop里面的name是否为空
            //抛自定义的业务异常
            throw new BusinessException("获取的参数不能为空");
        }
        //2.非法校验（百度AI智能审核） 名称、图片
        //使用 @TODO
        if (!BaiduAuditUtils.TextCensor(shop.getName())){//结果为false，抛异常，表示存在非法文本
            //抛自定义业务异常
            throw new BusinessException("您你输入的文字信息存在敏感或违规，请仔细检查！！！");
        }

        /*二. 业务校验*/
        //1.店铺不能被注册
         Shop shopTmp = shopMapper.loadByName(shop.getName());//使用shopTmp来接收获取的店铺名
         if (shopTmp !=null){//判断店铺名是不是null
             //抛自定义的业务异常
             throw new BusinessException("店铺名称已经存在，请直接登录");
         }
         //2.员工employee是否曾经已经存在
        Employee admin = shop.getAdmin();
        Employee empTmp = employeeMapper.loadByUsername(admin.getUsername());
        if(empTmp != null && empTmp.getShop_id() != null){//判断员工和对应的店铺是不是null
            //抛自定义的业务异常
            //System.out.println("店铺名称已经存在，请直接登录");
            throw new BusinessException("管理员不能管理多个店铺了");
        }
        //3. 员工不存在，添加员工
        if(empTmp == null){
            //存储employee,新增员工
           // employeeMapper.save(admin);//返回自增id
            //把employee相关业务交给service自己封装
            employeeService.add(admin);
            empTmp = admin;
        }
        //不管是新增和还是从数据库查询出原来的，到这里，都有员工了，不用再判断了
        //1.存储shop
        shop.setAdminId(empTmp.getId());
        shopMapper.save(shop);//返回自增ID
        //很容易忘记 需要重新修改employee中的shopId
        empTmp.setShop_id(shop.getId());
        //把employee相关业务交给service自己封装
        employeeService.update(empTmp);//empployeeMapper => employeeService
    }

    /**
     * 商户信息审核 通过
     * @param shopAuditLog
     */
    @Override
    public void pass(ShopAuditLog shopAuditLog) {
        //一. 需要将状态信息改为待激活
        //获取审核的商户id
        Shop shop = shopMapper.loadById(shopAuditLog.getShopId());
        //已经审核通过，就直接修改为审核通过的状态
        shop.setState(1);
        //去数据库修改状态（state）
        shopMapper.update(shop);
        //二. 记录审核日志，设置当前的登录人，把信息保存到数据库对应的日志管理
        shopAuditLog.setAuditId(334L);//获取登录人的id
        shopAuditLogMapper.save(shopAuditLog); //把登录人id存入,用来携带到日志
        //三. 审核通过发送激活邮件
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        //设置发送人
        mailMessage.setFrom("2214408710@qq.com");
        //邮件主题
        mailMessage.setSubject("商户审核认证通过！！");
        //邮件内容
        mailMessage.setText("可以了");
        //收件人
        mailMessage.setTo("1436507587@qq.com");
        javaMailSender.send(mailMessage);
    }

    /**
     * 审核信息 驳回
     * @param shopAuditLog
     */
    @Override
    public void reject(ShopAuditLog shopAuditLog) {
        //一. 需要将状态信息改为驳回
        //获取审核的商户id
        Shop shop = shopMapper.loadById(shopAuditLog.getShopId());
        //已经审核通过，就直接修改为审核通过的状态
        shop.setState(-1);
        //去数据库修改状态（state）
        shopMapper.update(shop);
        /*Shop shop = shopMapper.loadById(shopAuditLog.getShopId());
        shop.setState(-1);*/
        //二. 记录审核日志，获取，把信息保存到数据库对应的日志管理
        shopAuditLog.setAuditId(334L);//获取登录人的id
        shopAuditLogMapper.save(shopAuditLog); //把登录人id存入,用来携带到日志
        //三. 审核发送驳回的邮件
        //1. 获取店长的邮箱
        //Shop shop = shopMapper.loadById(shopAuditLog.getShopId());
        System.out.println(shop.getId()); //49
        System.out.println(shop.getAdmin()); //null
        System.out.println(shop.getAdmin_id()); //344
        System.out.println(shop.getAdminId()); //null
        Employee employee = employeeMapper.loadById(shop.getAdmin_id());//查询到与对应employee表对应的id
        System.out.println(employee); //null 这里有问题，无法获取到employee --- 解决：数据库表t_shop里面 对应的admin_id的字段为空，把他设置对应的值即可

        //2. 给店长发送驳回的邮件
        //3. 在邮件里面添加修改信息的链接 与Register2.vue先联系
        //创建复杂邮件对象
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //发送复杂邮件的工具类
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("2214408710@qq.com");
            helper.setSubject("审核驳回");
            //第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>审核失败</h1><br>"+
                    "<span>失败原因："+shopAuditLog.getNote()+"</span><br>"+
                    "<a href='http://127.0.0.1:8081/#/register2?id="+shop.getId()+"'>点击修改资料</a>",true);
            //收件人-邮箱
            helper.setTo(employee.getEmail());//根据对应email发送激活信息
            //helper.setTo("1436507587@qq.com");

            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 拒绝通过审核
     * @param shopAuditLog
     */
    @Override
    public void nopass(ShopAuditLog shopAuditLog) {
        //一. 需要将状态信息改为待激活
        //获取审核的商户id
        Shop shop = shopMapper.loadById(shopAuditLog.getShopId());
        //已经审核通过，就直接修改为审核通过的状态
        shop.setState(-2);
        //去数据库修改状态（state）
        shopMapper.update(shop);
    }

    /**
     * 用来图表显示，审核状态
     * @return
     */
    @Override
    public List<ShopVo> queryStateCount() {
        //调用对应查询状态数量的方法
        return shopMapper.queryStateCount();
    }

}
